import type { CartItemResult } from '@/types/cart'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useCartStore = defineStore(
  'cart',
  () => {
    const cartList = ref<CartItemResult[]>([])

    // 初始化购物车
    const setCart = (value: CartItemResult[]) => {
      cartList.value = value
    }
    // 添加购物车
    const addCart = (value: CartItemResult) => {
      const existingItem = cartList.value.find((item) => item.id === value.id)
      if (existingItem) {
        existingItem.number += 1
      } else {
        cartList.value.push(value)
      }
    }
    // 清空购物车
    const clearCart = () => {
      cartList.value = []
    }
    return {
      cartList,
      setCart,
      addCart,
      clearCart,
    }
  },
  {
    persist: true,
  },
)
